﻿namespace Bizspoke.BizTalk.Adapter
{
    using Microsoft.BizTalk.ExplorerOM;
    using Microsoft.Win32;
    using System;
    using System.Data;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;

    [StructLayout(LayoutKind.Sequential, Size=1)]
    public struct Info
    {
        public const string EdiUriPrefix = "EDI://";
        public const string BtsAdminKey = @"SOFTWARE\Microsoft\BizTalk Server\3.0\Administration";
        public const string BtsProdKey = @"SOFTWARE\Microsoft\BizTalk Server\3.0";
        public const string ProductKey = @"SOFTWARE\Microsoft\EDI Subsystem for Microsoft BizTalk Server\4.0";
        public const string SubsystemGroupNameKey = "EdiSubsystemGroupName";
        public const string SubsystemUserNameKey = "EdiSubsystemUserName";
        public const string ProductResource = "InfoTxt.ParityName";
        public const string DefaultCatalog = "BizTalkEDIDb";
        public const string DefaultDocumentsHome = @"C:\Documents and Settings\All Users\Application Data\Microsoft\BizTalk Server 2004\EDI\Subsystem\";
        public const string DefaultServerHome = @"C:\Program Files\Microsoft BizTalk Server 2005\EDI\Subsystem\";
        public const string DefaultInstallPath = @"C:\Program Files\Microsoft BizTalk Server 2005\";
        private static readonly Guid _ConfigurationGuid;
        private static string _BtsMgmtDBServer;
        private static string _BtsMgmtDBName;
        private static string _EdiDBServer;
        private static string _EdiDBName;
        private static string _BtsTrackingDBName;
        private static string _BtsTrackingDBServer;
        private static string _BtsSubscriptionDBName;
        private static string _BtsSubscriptionDBServer;
        private static string _DefaultBizTalkHostName;
        private static BtsCatalogExplorer _catalogExplorer;
        private static string _adapterName;
        public static Guid ConfigurationGuid
        {
            get
            {
                return _ConfigurationGuid;
            }
        }
        public static string BizTalkAdminNTGroup
        {
            get
            {
                return GetKeyValue(@"SOFTWARE\Microsoft\BizTalk Server\3.0\Administration", "BizTalkAdminNTGroup", "BizTalk Server Administrators");
            }
        }
        public static string EdiSubsystemGroupName
        {
            get
            {
                return GetKeyValue(@"SOFTWARE\Microsoft\EDI Subsystem for Microsoft BizTalk Server\4.0", "EdiSubsystemGroupName", "");
            }
        }
        public static string EdiSubsystemUserName
        {
            get
            {
                return GetKeyValue(@"SOFTWARE\Microsoft\EDI Subsystem for Microsoft BizTalk Server\4.0", "EdiSubsystemUserName", EdiDBUser);
            }
        }
        public static string BtsMgmtDBServer
        {
            get
            {
                if (_BtsMgmtDBServer == null)
                {
                    return GetKeyValue(@"SOFTWARE\Microsoft\BizTalk Server\3.0\Administration", "MgmtDBServer", SystemInformation.ComputerName);
                }
                return _BtsMgmtDBServer;
            }
            set
            {
                _BtsMgmtDBServer = value;
            }
        }
        public static string BtsMgmtDBName
        {
            get
            {
                if (_BtsMgmtDBName == null)
                {
                    return GetKeyValue(@"SOFTWARE\Microsoft\BizTalk Server\3.0\Administration", "MgmtDBName", "BizTalkMgmtDB");
                }
                return _BtsMgmtDBName;
            }
            set
            {
                _BtsMgmtDBName = value;
            }
        }
        public static void OverrideBtsMgmtDatabase(string connectionStr)
        {
            string[] strArray = connectionStr.Split(new char[] { ';' });
            if (strArray != null)
            {
                foreach (string str in strArray)
                {
                    string[] strArray2 = str.Split(new char[] { '=' });
                    if ((strArray2 != null) && (2 == strArray2.Length))
                    {
                        if ("Database" == strArray2[0])
                        {
                            BtsMgmtDBName = strArray2[1];
                        }
                        else if ("Server" == strArray2[0])
                        {
                            BtsMgmtDBServer = strArray2[1];
                        }
                    }
                }
            }
        }

        public static string EdiDBServer
        {
            get
            {
                if (_EdiDBServer == null)
                {
                    _EdiDBServer = GetKeyValue(@"SOFTWARE\Microsoft\EDI Subsystem for Microsoft BizTalk Server\4.0", "DatabaseServer", BtsMgmtDBServer);
                    OverrideEdiDatabase(new BtsMgmtDbInfo());
                }
                return _EdiDBServer;
            }
            set
            {
                _EdiDBServer = value;
            }
        }
        public static string EdiDBName
        {
            get
            {
                if (_EdiDBName == null)
                {
                    _EdiDBName = GetKeyValue(@"SOFTWARE\Microsoft\EDI Subsystem for Microsoft BizTalk Server\4.0", "Database", "BizTalkEDIDb");
                    OverrideEdiDatabase(new BtsMgmtDbInfo());
                }
                return _EdiDBName;
            }
            set
            {
                _EdiDBName = value;
            }
        }
        public static void OverrideEdiDatabase(DbInfo dbInfo)
        {
            DataTable table = SqlHelper.ExecuteProc("sp_GetBackupDatabaseLocation", new string[] { "@DefaultDatabaseName=EDI" }, dbInfo);
            if ((table != null) && (1 == table.Rows.Count))
            {
                DataRow row = table.Rows[0];
                EdiDBName = Convert.ToString(row["DatabaseName"]).Trim();
                EdiDBServer = Convert.ToString(row["ServerName"]).Trim();
            }
        }

        public static string EdiDBUser
        {
            get
            {
                return GetKeyValue(@"SOFTWARE\Microsoft\EDI Subsystem for Microsoft BizTalk Server\4.0", "DatabaseUser", @".\unknown");
            }
        }
        public static string BtsTrackingDBName
        {
            get
            {
                if (_BtsTrackingDBName == null)
                {
                    _BtsTrackingDBName = "BizTalkDTADb";
                    OverrideBtsTrackingDatabase(new BtsMgmtDbInfo());
                }
                return _BtsTrackingDBName;
            }
            set
            {
                _BtsTrackingDBName = value;
            }
        }
        public static string BtsTrackingDBServer
        {
            get
            {
                if (_BtsTrackingDBServer == null)
                {
                    _BtsTrackingDBServer = SystemInformation.ComputerName;
                    OverrideBtsTrackingDatabase(new BtsMgmtDbInfo());
                }
                return _BtsTrackingDBServer;
            }
            set
            {
                _BtsTrackingDBServer = value;
            }
        }
        public static void OverrideBtsTrackingDatabase(DbInfo dbInfo)
        {
            DataTable table = SqlHelper.ExecuteQuery("SELECT TrackingDBName, TrackingDBServerName FROM adm_Group", dbInfo);
            if ((table != null) && (0 < table.Rows.Count))
            {
                DataRow row = table.Rows[0];
                BtsTrackingDBName = Convert.ToString(row["TrackingDBName"]).Trim();
                BtsTrackingDBServer = Convert.ToString(row["TrackingDBServerName"]).Trim();
            }
        }

        public static string BtsSubscriptionDBName
        {
            get
            {
                if (_BtsSubscriptionDBName == null)
                {
                    _BtsSubscriptionDBName = "BizTalkMsgBoxDb";
                    DataTable table = SqlHelper.ExecuteQuery("SELECT SubscriptionDBName FROM adm_Group", new BtsMgmtDbInfo());
                    if ((table != null) && (table.Rows.Count > 0))
                    {
                        DataRow row = table.Rows[0];
                        _BtsSubscriptionDBName = Convert.ToString(row["SubscriptionDBName"]).Trim();
                    }
                }
                return _BtsSubscriptionDBName;
            }
        }
        public static string BtsSubscriptionDBServer
        {
            get
            {
                if (_BtsSubscriptionDBServer == null)
                {
                    _BtsSubscriptionDBServer = SystemInformation.ComputerName;
                    DataTable table = SqlHelper.ExecuteQuery("SELECT SubscriptionDBServerName FROM adm_Group", new BtsMgmtDbInfo());
                    if ((table != null) && (table.Rows.Count > 0))
                    {
                        DataRow row = table.Rows[0];
                        _BtsSubscriptionDBServer = Convert.ToString(row["SubscriptionDBServerName"]).Trim();
                    }
                }
                return _BtsSubscriptionDBServer;
            }
        }
        public static string DefaultBizTalkHostName
        {
            get
            {
                if (_DefaultBizTalkHostName == null)
                {
                    _DefaultBizTalkHostName = "BizTalkServerApplication";
                    DataTable table = SqlHelper.ExecuteQuery("SELECT Name FROM adm_Host WHERE Id = (SELECT DefaultHostId FROM adm_Group)", new BtsMgmtDbInfo());
                    if ((table != null) && (table.Rows.Count > 0))
                    {
                        DataRow row = table.Rows[0];
                        _DefaultBizTalkHostName = Convert.ToString(row["Name"]).Trim();
                    }
                }
                return _DefaultBizTalkHostName;
            }
        }
        public static string DocumentsHome
        {
            get
            {
                string str = @"C:\Documents and Settings\All Users\Application Data\Microsoft\BizTalk Server 2004\EDI\Subsystem\";
                DataTable table = SqlHelper.ExecuteQuery("SELECT documentshome FROM parame");
                if ((table != null) && (table.Rows.Count > 0))
                {
                    DataRow row = table.Rows[0];
                    str = Convert.ToString(row["documentshome"]).Trim();
                }
                return str;
            }
        }
        public static string ServerHome
        {
            get
            {
                return (InstallPath + @"EDI\Subsystem\");
            }
        }
        public static string InstallPath
        {
            get
            {
                return GetKeyValue(@"SOFTWARE\Microsoft\BizTalk Server\3.0", "InstallPath", @"C:\Program Files\Microsoft BizTalk Server 2005\");
            }
        }
        public static BtsCatalogExplorer CatalogExplorer
        {
            get
            {
                if (_catalogExplorer == null)
                {
                    _catalogExplorer = new BtsCatalogExplorer();
                    _catalogExplorer.ConnectionString = string.Format("SERVER={0};DATABASE={1};Integrated Security=SSPI", BtsMgmtDBServer, BtsMgmtDBName);
                }
                return _catalogExplorer;
            }
        }
        public static void CatalogRefresh()
        {
            CatalogExplorer.ConnectionString = string.Format("SERVER={0};DATABASE={1};Integrated Security=SSPI", BtsMgmtDBServer, BtsMgmtDBName);
            CatalogExplorer.Refresh();
        }

        public static string AdapterName
        {
            get
            {
                if (_adapterName == null)
                {
                    _adapterName = "EDI";
                    foreach (ProtocolType type in CatalogExplorer.ProtocolTypes)
                    {
                        if (type.ConfigurationGuid == ConfigurationGuid)
                        {
                            _adapterName = type.Name;
                            break;
                        }
                    }
                }
                return _adapterName;
            }
        }
        public static string GetKeyValue(string keyPath, string keyItem, string defVal)
        {
            string str = defVal;
            RegistryKey key = Registry.LocalMachine.OpenSubKey(keyPath);
            if (key != null)
            {
                str = Convert.ToString(key.GetValue(keyItem, defVal));
                key.Close();
            }
            return str;
        }

        static Info()
        {
            _ConfigurationGuid = new Guid("FF1E9295-1073-487F-BFAE-A78E962F6D35");
            _BtsMgmtDBServer = null;
            _BtsMgmtDBName = null;
            _EdiDBServer = null;
            _EdiDBName = null;
            _BtsTrackingDBName = null;
            _BtsTrackingDBServer = null;
            _BtsSubscriptionDBName = null;
            _BtsSubscriptionDBServer = null;
            _DefaultBizTalkHostName = null;
            _catalogExplorer = null;
            _adapterName = null;
        }
    }
}

